/** 解析链接的结果 */
interface AnalysisLinkResult {
  /** 地址 */
  url: string
  /** 地址参数 */
  query: Record<string, any>
}

/** 解析 url 参数配置 */
export interface ParseUrlParamsOptions {
  /** 是否需要 decode 参数 */
  decode?: boolean
}

interface IParams {
  /** 赋值分隔符 */
  assignment?: string
  /** 多个属性之间的分隔符 */
  separator?: string
}

export function getDataType(data: unknown): string {
  return Object.prototype.toString.call(data).slice(8, -1).toLowerCase()
}

export function useLink() {
  const parseParams = (obj: Record<number | string, any>, param?: IParams): string => {
    const { assignment = '=', separator = '&' } = param || {}
    const _type = getDataType(obj)

    const res = []
    if (_type === 'array') return ''
    if (_type !== 'object') return ''

    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        res.push(`${key}${assignment}${obj[key]}`)
      }
    }
    return res.join(separator)
  }

  /**
   * 解析链接参数
   * @param urlParams
   * @returns
   */
  const parseUrlParams = (urlParams: string, options?: ParseUrlParamsOptions) => {
    const { decode } = Object.assign({}, options)
    const regex = /([^&=]+)=([^&]*)/g
    let match
    const params: Record<string, string> = {}
    while ((match = regex.exec(urlParams))) {
      const key = match[1]
      const value = match[2]
      if (decode) {
        params[decodeURIComponent(key)] = decodeURIComponent(value)
      } else {
        params[key] = value
      }
    }
    return params
  }

  /** 解析链接 */
  const analysisLink = (link: string): AnalysisLinkResult => {
    const [url, querys] = (link || '').split('?')

    return {
      url,
      query: parseUrlParams(`${querys || ''}`),
    }
  }

  /**
   * 组装链接
   * @param params
   * @returns 链接地址 url?xxx
   */
  const assembleLink = (url: string, query: Record<string, string>): string => {
    // eslint-disable-next-line prefer-const
    let { url: _url, query: _query } = analysisLink(url)
    const linkArr: string[] = [_url]

    _query = Object.assign(_query, query)

    if (Object.entries(_query).length) {
      linkArr.push(parseParams(_query))
    }

    return linkArr.join('?')
  }

  return {
    parseUrlParams,
    analysisLink,
    assembleLink,
  }
}
